<?php
//LIBRARY OF ALL PLAYER DATA
//

//load and create player object
function getPlayerData($facebook_id){

try {
    $query = "SELECT * FROM `player` WHERE `facebook_id` = $facebook_id ";

    $result = mysql_query($query);

    if ($result) {
        $row = mysql_fetch_object($result);
    } else {
        $row = null;
    }

    return $row;

} catch (Exception $exc) {
    echo $exc->getTraceAsString();
}
}

//insert a new player
function insertNewPlayer($facebook_id){

try {
    $query = "INSERT INTO `player` (`facebook_id`) VALUES ($facebook_id);";

    $result = mysql_query($query);

    return $result;

} catch (Exception $exc) {
        echo $exc->getTraceAsString();
}

}

//update all player data
function updatePlayerData($player){

    $player = checkPlayerAllData($player);

    $query = "UPDATE `player` SET
        `experience` = $player->experience,
        `health` = $player->health,
        `health_max` = $player->health_max,
        `stamina` = $player->stamina,
        `stamina_max` = $player->stamina_max,
        `strength` = $player->strength,
        `dexterity` = $player->dexterity,
        `skill` = $player->skill,
        `energy` = $player->energy,
        `coins` = $player->coins,
        `loc_x` = $player->loc_x,
        `loc_y` = $player->loc_y,
        `last_play` = NOW()
        WHERE `player`.`id` = $player->id LIMIT 1";

    $result = mysql_query($query);

    return $result;
}

function checkPlayerAllData($player){

    $player->health = ($player->health > $player->health_max) ? $player->health_max : $player->health;
    $player->stamina = ($player->stamina > $player->stamina_max) ? $player->stamina_max : $player->stamina;

    $player->loc_x = ($player->loc_x < MAP_X_LOW) ? MAP_X_LOW : $player->loc_x;
    $player->loc_y = ($player->loc_y < MAP_Y_LOW) ? MAP_Y_LOW : $player->loc_y;
    $player->loc_x = ($player->loc_x > MAP_X_HIGH) ? MAP_X_HIGH : $player->loc_x;
    $player->loc_y = ($player->loc_y > MAP_Y_HIGH) ? MAP_Y_HIGH : $player->loc_y;

    return $player;
}


//get player map location details
function getPlayerLocation($player) {

    //get the player's location co-odinates
    $playerX = $player->loc_x;
    $playerY = $player->loc_y;

    $query = "SELECT * FROM `map` WHERE `x` = $playerX AND `y` = $playerY ORDER BY `x`, `y` LIMIT 0,1";

    $result = mysql_query($query);

    if ($result) {
        $row = mysql_fetch_object($result);
    }

    return $row; //map location object

}

?>
